package com.cmy.web.config;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

import javax.annotation.Resource;

/**
 * @Author:Cmy
 * @Date:2022/11/22-11:47
 * @Description:
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    //国际化拦截器
    @Resource(name = "LocaleChangeInterceptor")
    private LocaleChangeInterceptor localeChangeInterceptor;
    @Value("${virtual.path}")
    private String virtualPath;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加locale拦截器
        registry.addInterceptor(localeChangeInterceptor);
    }

    //解决跨域问题
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    //静态资源处理
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String location = FilenameUtils.separatorsToSystem("file:"+virtualPath);//"file:D:/CapImages_Test/"
        registry.addResourceHandler("/**").addResourceLocations(location,"classpath:/static/","classpath:/");
    }
}

    